<template>
  <div class="contract-sign-container">
    <!-- 侧边导航栏 -->
    <el-aside width="260px" class="sidebar">
      <div class="sidebar-header">
        <h3 class="title">行业分类</h3>
        <el-divider />
      </div>
      <el-menu
        :default-active="activeCategory"
        @select="handleCategoryChange"
        class="industry-menu"
      >
        <el-menu-item
          v-for="category in industryCategories"
          :key="category.value"
          :index="category.value"
        >
          <el-icon class="menu-icon"><OfficeBuilding /></el-icon>
          <span>{{ category.label }}</span>
        </el-menu-item>
      </el-menu>
      <div class="quick-links">
        <el-divider>快捷操作</el-divider>
        <el-button
          v-for="link in quickLinks"
          :key="link.path"
          :type="link.type"
          class="quick-link-btn"
          @click="router.push(link.path)"
        >
          <el-icon v-if="link.icon" class="btn-icon"
            ><component :is="link.icon"
          /></el-icon>
          {{ link.label }}
        </el-button>
      </div>
    </el-aside>

    <!-- 主体内容 -->
    <el-main class="main-content">
      <!-- 合同条款区域 -->
      <div class="contract-section card-container">
        <div class="section-header">
          <h3 class="section-title">合同条款</h3>
          <el-button type="info" plain @click="downloadTemplate"
            >下载模板</el-button
          >
        </div>
        <div class="contract-content">
          <VueVirtualScroller
            v-if="contractClauses.length"
            :items="contractClauses"
            :item-height="getItemHeight"
            class="virtual-scroller"
          >
            <template #default="{ item }">
              <div class="clause-item" :class="item.type">
                <!-- 标题类型 -->
                <template v-if="item.type === 'title'">
                  <h4 :class="`clause-title level-${item.level}`">
                    {{ item.content }}
                  </h4>
                </template>

                <!-- 段落类型 -->
                <template v-if="item.type === 'paragraph'">
                  <p class="clause-paragraph">
                    {{ renderTemplate(item.content) }}
                  </p>
                </template>

                <!-- 列表类型 -->
                <template v-if="item.type === 'list'">
                  <ul class="clause-list">
                    <li v-for="(listItem, index) in item.items" :key="index">
                      {{ renderTemplate(listItem) }}
                    </li>
                  </ul>
                </template>

                <!-- 子条款类型 -->
                <template v-if="item.type === 'clause'">
                  <div class="clause-subitem">
                    <span class="clause-number">{{ item.number }}</span>
                    <span class="clause-text">{{
                      renderTemplate(item.content)
                    }}</span>
                  </div>
                </template>
              </div>
            </template>
          </VueVirtualScroller>
          <el-empty v-else description="暂无合同条款" />
        </div>
      </div>

      <!-- 电子签名区域 -->
      <div class="signature-section card-container">
        <div class="section-header">
          <h3 class="section-title">
            电子签名
            <el-tag :type="signatureData ? 'success' : 'warning'" effect="dark">
              {{ signatureData ? '已完成' : '未完成' }}
            </el-tag>
          </h3>
          <div class="signature-tips">（请使用鼠标或触控笔签名）</div>
        </div>
        <signature-pad
          ref="signaturePad"
          :options="{ penColor: '#409EFF', backgroundColor: '#f8f9fa' }"
          class="signature-pad"
        />
      </div>

      <!-- 企业信息表单 -->
      <div class="form-section card-container">
        <h3 class="section-title">企业信息填写</h3>
        <el-form
          ref="contractForm"
          :model="formData"
          :rules="mergedFormRules"
          label-width="120px"
          label-position="top"
        >
          <!-- 基础字段 -->
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="公司名称" prop="companyName">
                <el-input
                  v-model="formData.companyName"
                  placeholder="请输入营业执照上的公司全称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="统一社会信用代码" prop="uscc">
                <el-input
                  v-model="formData.uscc"
                  placeholder="请输入18位统一社会信用代码"
                  maxlength="18"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 动态字段 -->
          <template v-for="field in dynamicFields" :key="field.prop">
            <el-form-item
              :label="field.label"
              :prop="field.prop"
              :rules="field.rules"
            >
              <component
                :is="field.component"
                v-model="formData[field.prop]"
                v-bind="getComponentProps(field)"
              >
                <template v-if="field.options">
                  <el-option
                    v-for="opt in field.options"
                    :key="opt"
                    :label="opt"
                    :value="opt"
                  />
                </template>
              </component>
            </el-form-item>
          </template>

          <!-- 地址选择 -->
          <el-form-item label="公司地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder="请选择或输入详细地址"
              class="address-input"
            >
              <template #append>
                <el-button @click="openMapPicker">
                  <el-icon><MapLocation /></el-icon>
                  地图选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item class="submit-btn">
            <el-button
              type="primary"
              :loading="submitting"
              @click="submitForm"
              size="large"
            >
              提交申请
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-main>
  </div>
</template>

<script setup>
import { ref, computed, watchEffect, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import SignaturePad from '@/components/SignaturePad.vue'
import VueVirtualScroller from 'vue3-virtual-scroller'
// 合同条款数据
const contractClauses = ref([])

// 模板渲染方法
const renderTemplate = (text) => {
  return text.replace(/\{\{(\w+)\}\}/g, (_, key) => {
    return formData.value[key] || '______'
  })
}

// 条款高度计算
const getItemHeight = (item) => {
  const baseHeight = {
    title: 45,
    paragraph: 65,
    list: item.items ? item.items.length * 28 + 20 : 60,
    clause: 40
  }
  return baseHeight[item.type] || 60
}

// 加载合同模板
const loadContractTemplate = async () => {
  contractClauses.value = [
    {
      type: 'title',
      content: '第一条 合同主体',
      level: 1
    },
    {
      type: 'paragraph',
      content: '甲方（承租方）：{{companyName}}，统一社会信用代码：{{uscc}}'
    },
    {
      type: 'title',
      content: '第二条 租赁物信息',
      level: 1
    },
    {
      type: 'list',
      items: [
        '租赁物名称：{{equipmentName}}',
        '规格型号：{{specification}}',
        '数量：{{quantity}}台/套'
      ]
    },
    {
      type: 'title',
      content: '第三条 租赁期限',
      level: 1
    },
    {
      type: 'clause',
      number: '3.1',
      content: '租赁期自{{startDate}}起至{{endDate}}止'
    },
    {
      type: 'clause',
      number: '3.2',
      content: '租赁期满后，如双方无异议自动续期一年'
    }
  ]
}

// 初始化加载合同模板
loadContractTemplate()

// 表单数据
const formData = ref({
  companyName: '示例科技有限公司',
  uscc: '91330101MA2A123456',
  equipmentName: '工业机器人',
  specification: 'IRB-6700',
  quantity: 5,
  startDate: '2024-01-01',
  endDate: '2025-12-31'
})

// 表单验证规则
const formRules = reactive({
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  uscc: [
    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
    { pattern: /^[0-9A-Z]{18}$/, message: '格式不正确', trigger: 'blur' }
  ]
  // 其他字段规则...
})
// 初始化路由
const router = useRouter()

// 行业分类数据
const industryCategories = ref([
  {
    label: '制造业',
    value: 'manufacture',
    fields: [
      { label: '生产能力', prop: 'productionCapacity', component: 'el-input' }
    ]
  },
  {
    label: '物流业',
    value: 'logistics',
    fields: [
      { label: '仓储容量', prop: 'storageCapacity', component: 'el-input' }
    ]
  }
])

// 当前选择的行业分类
const activeCategory = ref('manufacture')

// 监听行业变化
const dynamicFields = ref([])
watchEffect(() => {
  const category = industryCategories.value.find(
    (c) => c.value === activeCategory.value
  )
  dynamicFields.value = category?.fields || []
})

// 签名处理
const signaturePad = ref(null)
const signatureData = ref(null)

const saveSignature = () => {
  if (!signaturePad.value.isEmpty()) {
    signatureData.value = signaturePad.value.saveSignature()
    ElMessage.success('签名已保存')
  } else {
    ElMessage.warning('请先完成签名')
  }
}

const clearSignature = () => {
  signaturePad.value.clearSignature()
  signatureData.value = null
}

// 提交表单
const submitting = ref(false)
const formData2 = ref({ companyName: '' })
const submitForm = async () => {
  if (!signatureData.value) {
    ElMessage.warning('请先完成电子签名')
    return
  }
  submitting.value = true
  await new Promise((resolve) => setTimeout(resolve, 1000))
  ElMessage.success('合同提交成功')
  router.push('/management')
  submitting.value = false
}

// 加载合同条款
const loadContractTemplate2 = async () => {
  contractClauses.value = ['合同条款1', '合同条款2', '合同条款3']
}
loadContractTemplate()

// 合并表单验证规则
const mergedFormRules = computed(() => ({
  ...formRules,
  ...dynamicFields.value.reduce((rules, field) => {
    if (field.rules) rules[field.prop] = field.rules
    return rules
  }, {})
}))

// 增强组件props处理
const getComponentProps = (field) => {
  const baseProps = field.props || {}
  if (field.component === 'el-input-number') {
    return { ...baseProps, controlsPosition: 'right' }
  }
  return baseProps
}

// 新增下载模板功能
const downloadTemplate = () => {
  // 实现下载逻辑
  ElMessage.info('下载功能开发中')
}
const formRules2 = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }]
})
</script>

<style scoped>
.contract-sign-container {
  display: flex;
  height: 100vh;
  background: #f0f2f5;
}

.sidebar {
  background: #fff;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);

  .sidebar-header {
    padding: 16px 24px;

    .title {
      margin: 0;
      font-size: 16px;
      color: #333;
    }
  }

  .industry-menu {
    border-right: none;

    .menu-icon {
      font-size: 18px;
      margin-right: 8px;
    }
  }
}

.main-content {
  padding: 24px;
  background: #f0f2f5;
}

.card-container {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .section-title {
    margin: 0;
    font-size: 16px;
    color: #333;
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.virtual-scroller {
  height: 300px;
  border: 1px solid #ebeef5;
  border-radius: 4px;

  .clause-item {
    padding: 12px 16px;
    border-bottom: 1px solid #f5f7fa;
    transition: background 0.3s;

    &:hover {
      background: #f5f7fa;
    }

    .clause-index {
      color: #409eff;
      margin-right: 12px;
    }
  }
}

.signature-pad {
  height: 200px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin: 16px 0;
}

.signature-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.address-input {
  :deep(.el-input-group__append) {
    padding: 0 12px;
  }
}

.submit-btn {
  margin-top: 24px;
  text-align: center;
}

@media (max-width: 768px) {
  .contract-sign-container {
    flex-direction: column;
  }

  .el-col {
    span: 24 !important;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
